package cn.cuilan.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 *
 * @author zhang.yan
 * @date 2017/10/18
 */
public class EncodeUtils {

    /**
     * 加盐
     */
    private static final String SALT = "_cuilan";

    /**
     * MD5加密算法
     *
     * @param password 加密前的明文
     * @return 加密后的密文
     */
    public static String md5(String password) {
        // 加盐操作
        password = password + SALT;

        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        // 将密码转换为字符数组
        char[] charArray = password.toCharArray();
        // 创建byte数组
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toUpperCase();
    }

}
